package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.impl.UserServiceImpl;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    private HttpServletResponse httpServletResponse;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {

        //微信用户登录
        User user = userService.wxlogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //返回数据
        return Result.success(new UserLoginVO(user.getId(),user.getOpenid(),token));
    }

    @PostMapping("/logout")
    public Result logout() {
        httpServletResponse.setHeader("authentication","0");
        return Result.success();
    }
}
